//
//  CYYDVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/21.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYYDVC.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYHttpTool.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "UIImageView+WebCache.h"
#import "GCD.h"
#import "MBProgressHUD+LE.h"



@interface CYYDVC ()

@property(nonatomic, strong) GCDTimer *GCDTimer;
@property (weak, nonatomic) IBOutlet UITextField *dealCodeTF;
@property (weak, nonatomic) IBOutlet UIImageView *dealcodeImageView;
@property (weak, nonatomic) IBOutlet UITextField *imagedealCodeTF;
@property (nonatomic, strong) NSString *typeStr;
@property (weak, nonatomic) IBOutlet UIButton *imagedealcodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *yanzhengBtn;
@property (nonatomic, strong) NSString *mnoCertification;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UILabel *tishiLab;
@property (weak, nonatomic) IBOutlet UILabel *wenxintishiLab;


@end

@implementation CYYDVC


- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"中国移动授权";
     
     CYUser *user = [CYLoginHttpTool userData].user;
     _tishiLab.text = [NSString stringWithFormat:@"手机号码（请使用%@名下的号码进行认证）",user.name];
     _wenxintishiLab.text = [NSString stringWithFormat:@"1.请授权本人（%@）实名认证手机号（使用满3个月）。",user.name];

     
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(submitclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"确定" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;
     
    // Do any additional setup after loading the view from its nib.
}

-(void)loadimagestatues{
     //查询是否需要图形验证码
     NSDate *date = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     [CYHttpTool get10086WithURL:@"https://login.10086.cn/needVerifyCode.htm" params:@{@"accountType":@"01",@"account":_phoneTF.text,@"timestamp":timeSp} success:^(id json) {
          NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
          if (dic.count) {
               _typeStr = [dic objectForKey:@"needVerifyCode"];
               if (_typeStr.intValue == 1) {
                    //需要
                    _yanzhengBtn.hidden = NO;
                    [self loadimageyanzheng];
                    
                    
               }else{
                    //不需要
                    _imagedealCodeTF.placeholder = @"本次无需输入";
                    _imagedealCodeTF.enabled = NO;
                    _dealcodeImageView.hidden = YES;
                    _imagedealcodeBtn.hidden = YES;
                    
               }
          }
          
     } failure:^(NSError *error) {
          ;
          
     }];
     
}

- (IBAction)yanzhengBtn:(id)sender {
     [CYHttpTool get10086WithURL:@"https://login.10086.cn/verifyCaptcha" params:@{@"inputCode":_imagedealCodeTF.text} success:^(id json) {
          NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
          CYLog(@"dic = %@",dic);
          NSString *yzstr = [dic objectForKey:@"resultCode"];
          if (yzstr.intValue == 1) {
               CYAlertView(@"验证不通过!");
               
          }else if(yzstr&&yzstr.intValue == 0){
               CYAlertView(@"验证通过!");
               
          }
          
          
     } failure:^(NSError *error) {
          
     }];
     
}


-(void)loadimageyanzheng{
     if (_typeStr.intValue == 1) {
          //需要
          NSDate *date = [NSDate date];
          NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
          [CYHttpTool get10086WithURL:@"https://login.10086.cn/captchazh.htm" params:@{@"type":@"05",@"timestamp":timeSp} success:^(id json) {
               NSData *data = [NSData dataWithData:json];
               UIImage *image = [UIImage imageWithData:data];
               [_dealcodeImageView setImage:image];
               
          } failure:^(NSError *error) {
               
          }];
          
         }else{
     }
     
}


- (IBAction)getdealCodeClick:(id)sender {
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请输入手机号");
          return;
     }
     [self loadimagestatues];
     //获取验证码
          [CYHttpTool get10086WithURL:@"https://login.10086.cn/sendRandomCodeAction.action" params:@{@"userName":_phoneTF.text,@"type":@"01",@"channelID":@"12003"} success:^(id json) {
               NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
               if (jsonstr.intValue == 0) {
                    CYAlertView(@"发送成功！");
                    [self countdown:sender];
               }else{
                    CYAlertView(@"发送失败！");
               }
               
          } failure:^(NSError *error) {
               CYAlertView(@"网络连接失败");
          }];
          
}
/**
 *  倒计时
 */

- (void)countdown:(UIButton *)btn {
     self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
     
     CYWeakObject(weakself, self);
     __block int time = 119;
     [self.GCDTimer event:^{
          if (time < 1) {
               //设置界面的按钮显示 根据自己需求设置
               [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
               btn.userInteractionEnabled = YES;
               //            btn.backgroundColor = CYColor(79, 118, 245, 1);
               [weakself.GCDTimer destroy];
          } else {
               //        NSLog(@"time:%d", time);
               [btn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
               btn.userInteractionEnabled = NO;
               //            btn.backgroundColor = CYColor(211, 211, 211, 1);
          }
          time--;
     } timeInterval:NSEC_PER_SEC * 1];
     [self.GCDTimer start];
}

-(void)submitclick{
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请输入手机号");
          return;
     }
     if (_dealCodeTF.text.length == 0) {
          CYAlertView(@"请输入验证码");
          return;
          
     }
     if (_typeStr.intValue == 1 && _imagedealCodeTF.text.length == 0) {
          CYAlertView(@"请输入图形验证码");
          return;
     }
     if (_typeStr.intValue !=1 && _imagedealCodeTF.text == 0) {
          _imagedealCodeTF.text = @"";
     }
     NSDate *date = [NSDate date];
     NSString *logintimeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     CYUser *user = [CYLoginHttpTool userData].user;
     NSDictionary *params = [[NSDictionary alloc]init];
     // 1.获得请求管理者
     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     
     [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0" forHTTPHeaderField:@"User-Agent "];
     [manager.requestSerializer setValue:@"application/json, text/javascript, */*; q=0.01" forHTTPHeaderField:@"Accept"];
     [manager.requestSerializer setValue:@"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
     [manager.requestSerializer setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
     [manager.requestSerializer setValue:@"https://login.10086.cn/" forHTTPHeaderField:@"Referer"];
     params = @{@"accountType":@"01",@"account":_phoneTF.text,@"password":_dealCodeTF.text,@"pwdType":@"02",@"inputCode":_imagedealCodeTF.text,@"backUrl":@"http%3A%2F%2Fshop.10086.cn%2Fi%2F",@"rememberMe":@"0",@"channelID":@"12003",@"protocoool":@"https%3A",@"timestamp":logintimeSp};
     //登陆
     [MBProgressHUD showMessage:nil toView:self.view];
     [manager GET:@"https://login.10086.cn/login.htm" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
          [MBProgressHUD hideHUDForView:self.view animated:YES];
          NSDictionary *dic = responseObject;
          NSString *loginStr = [dic objectForKey:@"result"];
          NSString *artifact = [dic objectForKey:@"artifact"];
          NSString *assertAcceptURL = [dic objectForKey:@"assertAcceptURL"];
          if (loginStr&&artifact&&loginStr.intValue == 0&&assertAcceptURL) {
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               //验证是否登陆
               [CYHttpTool get10086WithURL:assertAcceptURL params:@{@"backUrl":@"http://shop.10086.cn/i/",@"artifact":artifact} success:^(id json) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
                    if (jsonstr) {
                         //执行获取数据
                         [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0" forHTTPHeaderField:@"User-Agent "];
                         [manager.requestSerializer setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
                         [manager.requestSerializer setValue:@"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
                         [manager.requestSerializer setValue:@"gzip, deflate, br" forHTTPHeaderField:@"Accept-Encoding"];
                         NSString *Urlstr = [NSString stringWithFormat:@"http://shop.10086.cn/i/v1/cust/info/%@",_phoneTF.text];
                         [MBProgressHUD showMessage:nil toView:self.view];
                         [manager GET:Urlstr parameters:@{@"time":@"20164814937909"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              NSDictionary *dic = responseObject;
                              if (dic.count) {
                                   [MBProgressHUD hideHUDForView:self.view animated:YES];
                                   NSDictionary *datadic = [dic objectForKey:@"data"];
                                   CYLog(@"dic = %@",datadic);
                                   if (datadic.count) {
                                        //处理数据，执行数据回传服务器
                                        NSString *inNetDate = [datadic objectForKey:@"inNetDate"];
                                        NSString *name = [datadic objectForKey:@"name"];
                                        if (name) {
                                             _mnoCertification = @"1";
                                             
                                        }else{
                                             _mnoCertification = @"0";
                                        }
                                        
                                        NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
                                        [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
                                        [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
                                        NSDate *inputDate = [inputFormatter dateFromString:inNetDate];
                                        NSString *netDateStr = [NSString stringWithFormat:@"%ld", (long)[inputDate timeIntervalSince1970]];
                                        
                                        double aNumber = [logintimeSp doubleValue];
                                        //网龄时间
                                        double netnumber = [netDateStr doubleValue];
                                        int daycount = (aNumber-netnumber)/60/60/24/30;//月为单位
                                        CYLog(@"datcount = %d",daycount);
                                        NSString *mnoAge = [NSString stringWithFormat:@"%d",daycount];
                                        CYLog(@"mnoAge = %@",mnoAge);
                                        if (daycount&&_mnoCertification) {
                                             //执行运营商数据保存
                                              [MBProgressHUD showMessage:nil toView:self.view];
                                             [CYHttpTool postWithURL:[CYURL shared].saveMno params:@{@"userId":user.userId,@"token":user.token,@"mnoCertification":_mnoCertification,@"mnoAge":mnoAge,@"name":name,@"phone":_phoneTF.text} success:^(id json) {
                                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                  CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
                                                  if (jsoninfo.isSuccess) {
                                                       [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                       CYAlertView(jsoninfo.message);                                                       //发送通知认证成功
                                                       [[NSNotificationCenter defaultCenter] postNotificationName:@"CYYYSNotification" object:nil userInfo:nil];
                                                       [self.navigationController popViewControllerAnimated:YES];

                                                  }else{
                                                       CYAlertView(@"授权失败");
                                                       [MBProgressHUD hideHUDForView:self.view animated:YES];

                                                  }
                                                  
                                                  
                                             } failure:^(NSError *error) {
                                                  CYAlertView(@"授权失败");
                                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                  
                                             }];
                                             
                                        }else{
                                             CYAlertView(@"授权失败!");
                                             [MBProgressHUD hideHUDForView:self.view animated:YES];

                                        }
                                        
                                   }else{
                                         CYAlertView(@"授权失败!");
                                        [MBProgressHUD hideHUDForView:self.view animated:YES];

                                   }
                                   
                              }else{
                                    CYAlertView(@"授权失败!");
                                   [MBProgressHUD hideHUDForView:self.view animated:YES];

                              }
                              
                         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                              CYAlertView(@"授权失败");
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              
                         }];
                         
                    }else{
                        CYAlertView(@"授权失败!");
                         [MBProgressHUD hideHUDForView:self.view animated:YES];

                    }

               } failure:^(NSError *error) {
                    CYAlertView(@"授权失败");
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
               }];
               
          }else{
               CYAlertView(@"授权失败!");
               [MBProgressHUD hideHUDForView:self.view animated:YES];

          }
          
      }failure:^(AFHTTPRequestOperation *  operation, NSError *  error) {
           CYAlertView(@"授权失败");
           [MBProgressHUD hideHUDForView:self.view animated:YES];
          
     }];
     
}


- (IBAction)imagechangeClick:(id)sender {
     NSDate *date = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     [CYHttpTool get10086WithURL:@"https://login.10086.cn/captchazh.htm" params:@{@"type":@"05",@"timestamp":timeSp} success:^(id json) {
          NSData *data = [NSData dataWithData:json];
          UIImage *image = [UIImage imageWithData:data];
          [_dealcodeImageView setImage:image];
          
     } failure:^(NSError *error) {
          
     }];
     
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
